package controllers

import javax.inject.Inject
import play.api.Logging
import play.api.data.Form
import play.api.data.Forms._
import play.api.mvc._
import services.freenas.FreeNASManage

import scala.concurrent.{ExecutionContext, Future}

class UserNasController @Inject()(nas: FreeNASManage,
                                  cc: ControllerComponents
                                 )(implicit exec: ExecutionContext, parser: BodyParsers.Default)
  extends AbstractController(cc) with play.api.i18n.I18nSupport with RequestAsJson with Logging {

  val userForm: Form[NasUserInfo] = Form {
    mapping(
      "p1" -> nonEmptyText,
      "p2" -> nonEmptyText,
      "p3" -> default(text(minLength = 5, maxLength = 16), "Wy111111111111")
    )(NasUserInfo.apply)(NasUserInfo.unapply)
  }

  def index() = checkLogin(parser, exec,"wuyang").async { implicit request =>
    val accId = request.session.get("accid").getOrElse("-1").toInt
    nas.userInfo(accId).map(arr => Ok(views.html.nas.profile(arr)))
  }

  def userUpdate() = checkLogin(parser, exec,"wuyang").async { implicit request =>
    val accountId = request.session.get("accid").getOrElse("-1").toInt

    userForm.bindFromRequest().fold(
      //      errorForm => Future.successful(Ok(views.html.nas.profile(Array("nas_profile","readonly"),errorForm))),
      errorForm => Future.successful(Redirect(routes.UserNasController.index())),
      p => {
        logger.debug(p.toString)
        val password = p.p3
        val username = p.p1
        val group = p.p2
        if ((!security.Checked.isCharOfName(username)) && (username.length < 6 || username.length > 16)) {
          logger.info(p.toString + s"username:$username char or length error")
          Future(Ok("共享用户名不合要求，请修改!"))
        }
        else if ((!security.Checked.isCharOfPassword(password)) && (password.length < 6 || password.length > 36)) {
          logger.info(p.toString + s"password:${password} char or length error")
          Future(Ok("密码不合要求，请修改！\n密码需同时包含字母和数字。"))
        }
        else {
          nas.userUpdate(accountId, username, password, group).map { r =>
            Ok(r)
          }
        }
      }
    )
  }

}
